﻿using System;
using System.Threading;

namespace MyBasicLib.Extensions
{
    public static class EventArgExtensions
    {
        /// <summary>
        /// 
        /// </summary>
        /// <typeparam name="TEventArgs"></typeparam>
        /// <param name="e"></param>
        /// <param name="sender"></param>
        /// <param name="eventDelegate"></param>
        /// <remarks>
        /// 参考 CLR.via.Csharp.3rd.Edition
        /// </remarks>
        public static void Raise<TEventArgs>(this TEventArgs e,
                                             Object sender, ref EventHandler<TEventArgs> eventDelegate)
            where TEventArgs : EventArgs
        {
            // Copy a reference to the delegate field now into a temporary field for thread safety   
            EventHandler<TEventArgs> temp =
                Interlocked.CompareExchange(ref eventDelegate, null, null);

            // If any methods registered interest with our event, notify them   
            if (temp != null) temp(sender, e);
        }
    }
}